package org.wangblue.document;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.wangblue.common.Client;
import org.wangblue.dto.User;

import java.io.IOException;

/**
 * @Description: 添加文档
 * @Author: WangBlue
 * @Create: 2024-10-22 15:50
 * @Version: 1.0
 **/

public class AddDocument {
    private static final String INDEX_NAME = "user";
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = Client.getClient();
        // 1. 新增文档 - 请求对象
        IndexRequest request = new IndexRequest();

        try{
            // 2. 设置索引名称
            request.index(INDEX_NAME).id("1001");

            // 3. 设置文档内容
            User user = new User();
            user.setName("王蓝");
            user.setSex("男");
            user.setAge(25);

            // 4. 将对象转换为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(user);

            // 5. 添加文档数据, 数据格式为JSON字符串
            request.source(json, XContentType.JSON);

            // 6. 客服端发送请求, 获取响应对象
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);

            // 7. 打印响应结果
            System.out.println("_index:" + response.getIndex());
            System.out.println("_id:" + response.getId());
            System.out.println("_result:" + response.getResult());
        }catch (Exception e){
            e.printStackTrace();
        }

        // 8. 关闭客户端
        client.close();
    }
}
